package be.ipl.eBar.usecasesimpl;

import javax.ejb.EJB;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import be.ipl.eBar.dao.BiereDao;
import be.ipl.eBar.dao.CommandeDao;
import be.ipl.eBar.dao.UneCommandeDao;
import be.ipl.eBar.domaine.Biere;
import be.ipl.eBar.domaine.Commande;
import be.ipl.eBar.exceptions.ArgumentInvalideException;
import be.ipl.eBar.exceptions.EtatConversationnelIncompletException;
import be.ipl.eBar.usecases.GestionDUneCommande;

@Stateful
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class GestionDUneCommandeImpl implements GestionDUneCommande {

	@PersistenceContext(name = "eBar", type = PersistenceContextType.EXTENDED)
	private EntityManager entityManager;
	@EJB
	UneCommandeDao ucdao;
	@EJB
	CommandeDao cdao;
	@EJB
	BiereDao bdao;

	private Commande commande;

	@Override
	public void setCommande(Commande commande) throws ArgumentInvalideException {
		if (commande == null)
			throw new ArgumentInvalideException();
		if (commande.getId() == 0) {
			if (!entityManager.contains(commande)) {
				ucdao.enregistrer(commande);
			}
		} else {
			commande = cdao.recharger(commande.getId());
			commande = cdao.chargerBieres(commande);
		}
		this.commande = commande;
	}

	@Override
	public Commande ajouterBiere(Biere biere, int quantite)
			throws EtatConversationnelIncompletException {
		if (commande == null)
			throw new EtatConversationnelIncompletException();
		biere = bdao.recharger(biere.getId());
		commande.addQuantite(biere, quantite);
		return commande;
	}

	@Override
	public Commande supprimerBiere(Biere biere, int quantite)
			throws EtatConversationnelIncompletException {
		if (commande == null)
			throw new EtatConversationnelIncompletException();
		biere = bdao.recharger(biere.getId());
		commande.addQuantite(biere, -quantite);
		return commande;
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	@Remove
	@Override
	public Commande sauverCommande()
			throws EtatConversationnelIncompletException {
		if (this.commande == null)
			throw new EtatConversationnelIncompletException();
		if (commande.getBieres().size() == 0) {
			commande = null;
			return null;
		}
		entityManager.flush();
		return commande;
	}

}
